package com.dashihui.afford.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.dashihui.afford.AffordApp;
import com.dashihui.afford.R;
import com.dashihui.afford.business.BusinessOrder;
import com.dashihui.afford.business.BusinessUser;
import com.dashihui.afford.business.entity.EtySendToUI;
import com.dashihui.afford.common.base.BaseActivity;
import com.dashihui.afford.common.constants.AffConstans;
import com.dashihui.afford.common.constants.CommConstans;
import com.dashihui.afford.sqlite.SqliteShoppingCart;
import com.dashihui.afford.thirdapi.FastJSONHelper;
import com.dashihui.afford.thirdapi.greedsqlite.ShoppingCart;
import com.dashihui.afford.ui.activity.my.AtyMyAddress;
import com.dashihui.afford.ui.adapter.AdapterSettlement;
import com.dashihui.afford.ui.model.ModelDoAdd;
import com.dashihui.afford.ui.widget.WgtAlertDialog;
import com.dashihui.afford.util.number.UtilNumber;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.util.LogUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.lidroid.xutils.view.annotation.event.OnRadioGroupCheckedChange;

import java.util.List;
import java.util.Map;

public class AtySettlementAgain extends BaseActivity {

    @ViewInject(R.id.left_back)
    private ImageButton mLeftBack;
    @ViewInject(R.id.ibtn_userinfo)
    private ImageButton mIbtEditAddr;
    private BusinessUser mBllUser;
    private BusinessOrder mBllOrder;
    @ViewInject(R.id.noAddress)
    private TextView mNoAddress;
    @ViewInject(R.id.top_address)
    private LinearLayout mLytTopaddress;
    @ViewInject(R.id.addAddress)
    private LinearLayout mLytAddAddress;


    @ViewInject(R.id.username)
    private TextView mUserName;//用户名字
    @ViewInject(R.id.usersex)
    private TextView mUserSex;//性别
    @ViewInject(R.id.userphone)
    private TextView mUserPhone;//用户电话
    @ViewInject(R.id.useraddr)
    private TextView mUserAddr;//用户地址


    @ViewInject(R.id.payType)
    private RadioGroup mPayType;//支付方式
    @ViewInject(R.id.takeType)
    private RadioGroup takeType;//配送方式
    @ViewInject(R.id.delivery_remark)
    private TextView mRemarkTv;

    @ViewInject(R.id.goods_price)
    private TextView mGoodsPrice;//商品金额
    @ViewInject(R.id.stilpay_money)
    private TextView mPayMoney;//需付款
    @ViewInject(R.id.txtViewPrice)
    private TextView mPrice;//实付款

    @ViewInject(R.id.txtViewSettlement)
    private TextView mTxtViewSettlement;//提交订单

    @ViewInject(R.id.listView)
    private ListView mListView;

    @ViewInject(R.id.delivery_remark)
    private TextView mBtnRemakTv;

    private AdapterSettlement mAdapterSettlement;
    private List<ShoppingCart> mShopCartList;

    private ModelDoAdd mModelDoAdd;
    private String mOrderInfo;//从FragmentOrderState获取再来一单的订单信息
    private Map<String,Object> mMapObject;


    public static final String TAG = "WdtAppsFragment";
    private static final String ARG_POSITION = "position";
    public static final String ORDERINFO = "orderInfo";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.aty_settlement);
        ViewUtils.inject(this);
        getOrderInfo();
        mBllUser = new BusinessUser(this);
        mModelDoAdd = new ModelDoAdd();
        mBllOrder = new BusinessOrder(this);
        //支付方式初始化
        mModelDoAdd.setPaytype("1");
        //送货方式初始化
        mModelDoAdd.setTaketype("1");
        //初始化数据
        initData();
        getOrderInfo();
    }


    @Override
    protected void onResume() {
        LogUtils.e("是否登录================>" + AffordApp.isLogin());
        //是否登录
        if (!AffordApp.isLogin()) {
            //没有登录
            LogUtils.e("没有登录======isLogin==========>");
            Intent intent = new Intent(AtySettlementAgain.this, AtyLogin.class);
            intent.putExtra(CommConstans.Login.INTENT_KEY, CommConstans.Login.INTENT_VALUE_SETTLEMENT);
            startActivity(intent);
        }
        /****&&  设置店铺ID   &&******/
        if (AffordApp.getInstance().getEntityLocation() != null && AffordApp.getInstance().getEntityLocation().getSTORE() != null) {
            mModelDoAdd.setStoreid(AffordApp.getInstance().getEntityLocation().getSTORE().getID() + "");
        } else {
            LogUtils.e("null===Error====AtySettlement===>" + AffordApp.LOG_PHONE);
            finish();
        }

        //获取默认地址
        mBllUser.defaultAddress();
        LogUtils.e("登录======isLogin==========>");
        super.onResume();
    }


    @Override
    public void onSuccess(EtySendToUI beanSendUI) {
        if (beanSendUI != null) {
            switch (beanSendUI.getTag()) {
                case AffConstans.BUSINESS.TAG_USER_DEFAULTADDRESS://默认地址
                    LogUtils.e("onSuccess======默认地址========>" + beanSendUI.getInfo());
                    Map<String, String> defaultAddr = (Map<String, String>) beanSendUI.getInfo();
                    mNoAddress.setVisibility(View.GONE);
                    mLytTopaddress.setVisibility(View.VISIBLE);
                    mUserName.setText(defaultAddr.get("LINKNAME") + "");//用户名字
                    String sex = defaultAddr.get("SEX") + "";
                    /****&&  设置性别   &&******/
                    if ("1".equals(sex)) {
                        mUserSex.setText("先生 ");//性别
                        mModelDoAdd.setSex("先生 ");
                    } else {
                        mUserSex.setText("女士");//性别
                        mModelDoAdd.setSex("女士");
                    }
                    mUserPhone.setText(defaultAddr.get("TEL") + "");//用户电话
                    mUserAddr.setText(defaultAddr.get("COMMUNITYTITLE") + "" + defaultAddr.get("BUILDNAME") + "" + defaultAddr.get("UNITNAME") + "" + defaultAddr.get("ROOMNAME") + "");//用户地址
                    break;
                case AffConstans.BUSINESS.TAG_ORDER_SAVA://提交订单
                    Map<String, Object> order = (Map<String, Object>) beanSendUI.getInfo();
                    LogUtils.e("onSuccess======提交订单========>" + order);
                    if (order != null) {
                        Intent mapIntent = new Intent(this, AtySettlementOrder.class);
                        mapIntent.putExtra(AtySettlementOrder.ORDER_PRICE, order.get("AMOUNT") + "");
                        mapIntent.putExtra(AtySettlementOrder.ORDER_CODE, order.get("ORDERNUM") + "");
                        startActivity(mapIntent);
                        finish();
                    } else {
                        LogUtils.e("onSuccess======提交订单===error=====>" + order);
                    }
                    break;

                default:
                    LogUtils.e("onSuccess===default===========>" + beanSendUI);
                    break;
            }
        } else {
            LogUtils.e("onSuccess======AtyHome=========>" + beanSendUI);
        }
        //去提交订单按钮恢复
        mTxtViewSettlement.setEnabled(true);
    }

    @Override
    public void onFailure(EtySendToUI beanSendUI) {
        if (beanSendUI != null) {
            switch (beanSendUI.getTag()) {
                case AffConstans.BUSINESS.TAG_USER_DEFAULTADDRESS://默认地址
                    LogUtils.e("onFailure======默认地址========>" + beanSendUI.getInfo());
                    mNoAddress.setVisibility(View.VISIBLE);
                    mLytTopaddress.setVisibility(View.GONE);
                    break;
                case AffConstans.BUSINESS.TAG_ORDER_SAVA://提交订单
                    LogUtils.e("onFailure======提交订单========>" + beanSendUI.getInfo());
                    if (mDialog == null) {
                        mDialog = new WgtAlertDialog();
                    }
                    mDialog.show(this,
                            "确定",
                            beanSendUI.getInfo().toString(),
                            new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    mDialog.dismiss();
                                    AtySettlementAgain.this.finish();
                                }
                            }, false, false);
                    break;
                default:
                    LogUtils.e("onFailure===default===========>" + beanSendUI);
                    break;
            }
        } else {
            LogUtils.e("onFailure======AtySettlement=========>" + beanSendUI);
        }
        //去提交订单按钮恢复
        mTxtViewSettlement.setEnabled(true);
    }

    public void getOrderInfo(){
        Intent intent = getIntent();
        if (!"".equals(getIntent().getStringExtra(TAG)) && getIntent().getStringExtra(TAG) != null){
            mOrderInfo = intent.getStringExtra(ORDERINFO);
            mMapObject = (Map<String, Object>) FastJSONHelper.deserialize(mOrderInfo,AtyOrderState.class);
            LogUtils.e("getOrderInfo===========mMapObject==========>" + mMapObject);
        }
    }


    //支付方式
    @OnRadioGroupCheckedChange(R.id.payType)
    public void onPayTypeCheckedChanged(RadioGroup group, int checkedId) {
        LogUtils.e("onPayTypeCheckedChanged======AtySettlement=========>" + checkedId);
        /****&&  设置支付方式   &&******/
        switch (checkedId) {
            case R.id.confirm_weixin_cBoxAgree://线上支付
                mModelDoAdd.setPaytype("1");
                LogUtils.e("onPayTypeCheckedChanged======线上支付========>" + checkedId);
                break;
            case R.id.confirm_delivery_cBoxAgree://货到付款
                mModelDoAdd.setPaytype("2");
                LogUtils.e("onPayTypeCheckedChanged======货到付款=======>" + checkedId);
                break;
            default:
                break;
        }
    }

    //配送方式
    @OnRadioGroupCheckedChange(R.id.takeType)
    public void onTakeTypeCheckedChanged(RadioGroup group, int checkedId) {
        LogUtils.e("onTakeTypeCheckedChanged======AtySettlement=========>" + checkedId);
        switch (checkedId) {
            case R.id.confirm_store_cBoxAgree://门店配送
                mModelDoAdd.setTaketype("1");
                LogUtils.e("onTakeTypeCheckedChanged======门店配送=======>" + checkedId);
                break;
            case R.id.confirm_myself_cBoxAgree://上门自取
                mModelDoAdd.setTaketype("2");
                LogUtils.e("onTakeTypeCheckedChanged======上门自取=======>" + checkedId);
                break;
            default:
                break;
        }
    }

    /**
     * 提交订单
     *
     * @param v
     */
    @OnClick(R.id.txtViewSettlement)//提交订单
    public void onSettlementClick(View v) {
        //禁止多次提交
        mTxtViewSettlement.setEnabled(false);
        /**********  设置地址  **********/
        String address = mUserAddr.getText().toString().trim();
        mModelDoAdd.setAddress(address);
        /**********  收货人姓名 **********/
        String userName = mUserName.getText().toString().trim();
        mModelDoAdd.setLinkname(userName);
        /**********  收货人电话 **********/
        String phone = mUserPhone.getText().toString().trim();
        LogUtils.e("收货人电话============>" + mUserPhone);
        mModelDoAdd.setTel(phone);
        /**********  订单备注 **********/
        String describe = mRemarkTv.getText().toString().trim();
        mModelDoAdd.setDescribe(describe);

        mBllOrder.sava(mModelDoAdd);
    }

    @OnClick(R.id.left_back)//返回
    public void onBackClick(View v) {
        onBackPressed();
    }

    @OnClick(R.id.addAddress)
    public void onAddAdressClick(View v) {
        mBaseUtilAty.startActivity(AtyMyAddress.class);
    }

    /**
     * 动态设置listview高度
     *
     * @param listView
     */
    private void setlistViewHeigh(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        ((ViewGroup.MarginLayoutParams) params).setMargins(10, 10, 10, 10);
        listView.setLayoutParams(params);

    }

    @OnClick(R.id.lyt_remark)
    public void onLytRemarkClick(View v) {
        Intent intent = new Intent(AtySettlementAgain.this, AtySettlementRemark.class);
        startActivityForResult(intent, CommConstans.ADDRESS.MARS);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CommConstans.ADDRESS.MARS:
                if (data != null && data.getExtras().size() > 0) {
                    LogUtils.e("data========>" + data);
                    LogUtils.e("data.getExtras========>" + data.getExtras());
                    Bundle _remBunlde = data.getExtras();
                    String remText = _remBunlde.getString(AtySettlementRemark.REMARK);

                    LogUtils.e("==========》" + _remBunlde);
                    mRemarkTv.setText(remText);
                } else {
                    mRemarkTv.setText("");
                    mRemarkTv.setHint("配送备注（可选）");
                }
                break;
            default:
                break;
        }
    }

    /**
     * 初始化数据
     */
    private void initData() {
        if (AffordApp.getInstance().getEntityLocation() != null && AffordApp.getInstance().getEntityLocation().getSTORE() != null) {
            mShopCartList = SqliteShoppingCart.getInstance(this).getListShoppingCartByShopID(AffordApp.getInstance().getEntityLocation().getSTORE().getID() + "", true);
            LogUtils.e("商品列表个数=============>" + mShopCartList);
            LogUtils.e("商品列表个数=============>" + mShopCartList.size());
            mAdapterSettlement = new AdapterSettlement(this, mShopCartList);
            mListView.setAdapter(mAdapterSettlement);
            setlistViewHeigh(mListView);

            double _allNum = 0;
            double _allPrice = 0d;
            String goodsID = "";
            String count = "";
            for (int i = 0; i < mShopCartList.size(); i++) {
                double num = UtilNumber.DoubleValueOf(mShopCartList.get(i).getBuynum() + "");
                double price = UtilNumber.DoubleValueOf(mShopCartList.get(i).getSellprice() + "");
                double numPrice = UtilNumber.DoubleValueOf(num * price + "");
                if (i == (mShopCartList.size() - 1)) {
                    goodsID += mShopCartList.get(i).getID() + "";
                    count += UtilNumber.IntegerValueOf(mShopCartList.get(i).getBuynum()) + "";
                } else {
                    goodsID += mShopCartList.get(i).getID() + ",";
                    count += UtilNumber.IntegerValueOf(mShopCartList.get(i).getBuynum()) + ",";
                }
                _allNum += num;
                _allPrice += numPrice;
            }
            LogUtils.e("&&&&&&&&&&&&&&&&&===goodsID字符串================>" + goodsID);
            LogUtils.e("&&&&&&&&&&&&&&&&&===count字符串=============>" + count);
            LogUtils.e("&&&&&&&&&&&&&&&&&===数量===>" + _allNum);
            LogUtils.e("_&&&&&&&&&&&&&&&&&e===价格====>" + _allPrice);
            if (_allNum != 0) {
                mModelDoAdd.setGoodsid(goodsID);
                mModelDoAdd.setCount(count);
                mModelDoAdd.setAmount(UtilNumber.DoubleValueOf(_allPrice+"") + "");
                mGoodsPrice.setText("" + UtilNumber.DoubleValueOf(_allPrice+"")+ "");//商品金额
                mPayMoney.setText("" + UtilNumber.DoubleValueOf(_allPrice+"") + "");//需付款
                mPrice.setText("实付款：￥" + UtilNumber.DoubleValueOf(_allPrice+"") + "");//实付款
            }
        } else {
            LogUtils.e("null异常============================>");
            finish();
        }
    }
}
